package com.neusoft.elmboot.controller;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.neusoft.elmboot.po.*;
import com.neusoft.elmboot.po.vo.BusinessOrderVO;
import com.neusoft.elmboot.service.*;
import com.neusoft.elmboot.util.CommonUtil;
import com.neusoft.elmboot.util.response.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/elm/OrdersController")
public class OrdersController {

	@Autowired
	private OrdersService ordersService;

	@Autowired
	private UserService userService;

	@Autowired
	private BusinessService businessService;

	@Autowired
	private FoodService foodService;

	@Autowired
	private DeliveryAddressService deliveryAddressService;

	@RequestMapping("/createOrders")
	public ResultBody createOrders(Orders orders) throws Exception {
		try {
			orders.setOrderDate(CommonUtil.getCurrentDate());
			return ResultBody.success("添加订单成功！", ordersService.createOrders(orders));
		} catch (Exception e) {
			return ResultBody.error("添加订单失败！", -1);
		}
	}
	
	@RequestMapping("/getOrdersById")
	public ResultBody getOrdersById(@RequestParam Integer orderId) throws Exception{
		try {
			Orders orders = ordersService.getOrdersById(orderId);
			if (orders == null) {
				return ResultBody.error("不存在此订单！", null);
			}

			String address = deliveryAddressService.getDeliveryAddressById(orders.getDaId()).getAddress();
			Business business = businessService.getBusinessById(orders.getBusinessId());
			List<OrderDetailet> detailets = ordersService.getOrderDetailetByOrderId(orders.getOrderId());
			List<BusinessOrderVO> businessOrderVOList = new ArrayList<>();

			JSONObject object = new JSONObject();

			for (OrderDetailet detailet : detailets) {
				BusinessOrderVO businessOrderVO = BusinessOrderVO.builder()
						.foodName(detailet.getFoodName())
						.foodPrice(detailet.getFoodPrice())
						.quantity(detailet.getQuantity()).build();
				businessOrderVOList.add(businessOrderVO);
			}

			object.putOpt("address", address);
			object.putOpt("totalPrice", orders.getOrderTotal());
			object.putOpt("deliveryPrice", business.getDeliveryPrice());
			object.putOpt("priceDetails", businessOrderVOList);

			return ResultBody.success("获取订单信息成功！", object);
		} catch (Exception e) {
			return ResultBody.error("获取订单信息失败！", null);
		}
	}
	
	@RequestMapping("/listOrdersByUserId")
	public ResultBody listOrdersByUserId(String userId) throws Exception{
		try {
			List<Orders> ordersList = ordersService.listOrdersByUserId(userId);
			if (ordersList.isEmpty()) {
				return ResultBody.success();
			}
			JSONArray re = new JSONArray();
			for (Orders orders : ordersList) {
				String address = deliveryAddressService.getDeliveryAddressById(orders.getDaId()).getAddress();
				Business business = businessService.getBusinessById(orders.getBusinessId());
				List<OrderDetailet> detailets = ordersService.getOrderDetailetByOrderId(orders.getOrderId());
				List<BusinessOrderVO> businessOrderVOList = new ArrayList<>();

				for (OrderDetailet detailet : detailets) {
					BusinessOrderVO businessOrderVO = BusinessOrderVO.builder()
							.foodName(detailet.getFoodName())
							.foodPrice(detailet.getFoodPrice())
							.quantity(detailet.getQuantity()).build();
					businessOrderVOList.add(businessOrderVO);
				}

				JSONObject object = new JSONObject();
				object.putOpt("orderId", orders.getOrderId());
				object.putOpt("tel", orders.getUserId());
				object.putOpt("address", address);
				object.putOpt("businessName", business.getBusinessName());
				object.putOpt("businessAddress", business.getBusinessAddress());
				object.putOpt("totalPrice", orders.getOrderTotal());
				object.putOpt("deliveryPrice", business.getDeliveryPrice());
				object.putOpt("priceDetails", businessOrderVOList);
				object.putOpt("orderState", orders.getOrderState());

				re.add(object);
			}

			return ResultBody.success("获取成功！", re);
		} catch (Exception e) {
			return ResultBody.error("获取失败！", null);
		}
	}

	@RequestMapping("/payment")
	public ResultBody updateOrderState(@RequestParam Integer state,
									   @RequestParam Integer orderId) throws Exception{
		try {
			ordersService.updateOrderState(state,orderId);
			return ResultBody.success("支付成功", null);
		} catch (Exception e) {
			return ResultBody.error("支付失败", null);
		}
	}

	@RequestMapping("/business/orders")
	public ResultBody getBusinessOrders(@RequestParam String businessId) throws Exception{
		try {
			List<Orders> ordersList =  ordersService.listOrdersByBusinessId(businessId);
			if (ordersList.isEmpty()) {
				return ResultBody.error("获取失败！", null);
			}
			JSONArray re = new JSONArray();
			for (Orders o : ordersList) {
				JSONObject object = new JSONObject();

				User user = userService.getUserInfoById(o.getUserId());
				Business business = businessService.getBusinessById(o.getBusinessId());
				Double deliveryPrice = business.getDeliveryPrice();
				List<OrderDetailet> orderDetailets = ordersService.getOrderDetailetByOrderId(o.getOrderId());
				List<BusinessOrderVO> list = new ArrayList<>();
				for (OrderDetailet od : orderDetailets) {
					BusinessOrderVO vo = BusinessOrderVO.builder()
							.foodName(od.getFoodName())
							.foodPrice(od.getFoodPrice())
							.quantity(od.getQuantity()).build();

					list.add(vo);
				}

				object.putOpt("userName", user.getUserName());
				object.putOpt("userId", user.getUserId());
				object.putOpt("orderDetail", list);
				object.putOpt("orderTotal", o.getOrderTotal());
				object.putOpt("deliveryPrice", deliveryPrice);
				object.putOpt("orderState", o.getOrderState());

				re.add(object);
			}
			return ResultBody.success("获取成功！", re);
		} catch (Exception e) {
			return ResultBody.error("获取失败！", null);
		}
	}

	@RequestMapping("/user/cancelOrder")
	public ResultBody cancelOrder(@RequestParam Integer orderId) throws Exception{
		try {
			Orders orders = ordersService.getOrdersById(orderId);
			if (orders.getOrderState() == 0) {
				ordersService.cancelOrder(orderId);
				return ResultBody.success("订单已取消！", null);
			} else if (orders.getOrderState() == 1) {
				return ResultBody.error("已支付的订单不能直接取消，请联系商家！", null);
			}
			return ResultBody.error("不知道", null);
		} catch (Exception e) {
			return ResultBody.error("订单取消失败！", null);
		}
	}
}
